package com.scau402.web.controller.system;

import com.scau402.common.utils.DateUtils;
import com.scau402.common.utils.ip.IpUtils;
import com.scau402.system.domain.SysTenant;
import com.scau402.system.service.ISysTenantService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.scau402.common.core.controller.BaseController;
import com.scau402.common.core.domain.AjaxResult;
import com.scau402.common.core.domain.model.RegisterBody;
import com.scau402.common.utils.StringUtils;
import com.scau402.framework.web.service.SysRegisterService;
import com.scau402.system.service.ISysConfigService;

/**
 * 注册验证
 * 
 * @author ruoyi
 */
@RestController
public class SysRegisterController extends BaseController
{
    @Autowired
    private SysRegisterService registerService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private ISysTenantService sysTenantService;

    @PostMapping("/register")
    public AjaxResult register(@RequestBody RegisterBody user)
    {
        if (!("true".equals(configService.selectConfigByKey("sys.account.registerUser"))))
        {
            return error("当前系统没有开启注册功能！");
        }
        String msg = registerService.register(user);
        return StringUtils.isEmpty(msg) ? success() : error(msg);
    }

    /**
     * 住户自行注册接口
     *
     * @return
     */
    @PostMapping("/tenantRegister")
    public AjaxResult tenantRegister(@RequestBody SysTenant sysTenant) {
        AjaxResult ajax = AjaxResult.error();
        // 判断租户编号是否存在
        if (StringUtils.isNotEmpty(sysTenant.getTenantCode()) && !sysTenantService.checkTenantCodeUnique(sysTenant)) {
            ajax.put("error", "租户'" + sysTenant.getTenantCode() + "'注册失败，租户编号已存在");
            return ajax;
        }
        // 判断租户名称是否存在
        if (StringUtils.isNotEmpty(sysTenant.getTenantName()) && !sysTenantService.checkTenantNameUnique(sysTenant)) {
            ajax.put("error", "租户'" + sysTenant.getTenantName() + "'注册失败，租户名称已存在");
            return ajax;
        }
        ajax = AjaxResult.success();
        // 设置租户来源
        sysTenant.setTenantSource("注册");
        // 设置审核状态为未审核
        sysTenant.setReview("0");
        // 设置租户状态为停用
        sysTenant.setStatus("1");
        // 设置注册 IP
        sysTenant.setTenantRegisterIp(IpUtils.getIpAddr());
        // 设置注册时间
        sysTenant.setCreateTime(DateUtils.getNowDate());
        sysTenantService.insertSysTenant(sysTenant);
        return ajax.put("success", "租户'" + sysTenant.getTenantName() + "'注册成功");
    }
}
